package com.ccx.coachsite.downloadmgr;



import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.ccx.coachsite.util.DBHelper;

public class DownloadItemDao {
	private DBHelper dbHelper;
	private String table;
	
	public static final int DOWN = 0;
	public static final int INSTALL = 1;
	
	public DownloadItemDao(Context context,int type){
		dbHelper = new DBHelper(context);
		switch(type){
		case DOWN:
			table = "down_item";
			break;
		case INSTALL:
			table = "install_item";
			break;
		default:
			table = "down_item";
			break;
		}
	}
	
	public void addItem(DownloadItem item){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("sid", item.getSid());
		values.put("title", item.getTitle());
		values.put("icon_path", item.getIconPath());
		values.put("pkg_name", item.getPkgName());
		values.put("icon_url", item.getIconUrl());
		values.put("avail_version", item.getAvailVersion());
		values.put("file_bytes", item.getFileBytes());
		values.put("download_url", item.getDownloadUrl());
		values.put("file_path", item.getFilePath());
		db.insert(table, null, values);
		db.close();
	}
	
	public void delete(String sid){
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.delete(table, "sid=?", new String[]{sid});
		db.close();
	}
	
	public List<DownloadItem> getItemList(){
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.query(table, new String[]{
			"sid","title","icon_path","icon_url","pkg_name","avail_version","file_bytes","download_url","file_path"}
			, null, null, null, null, null);
		List<DownloadItem> list = new ArrayList<DownloadItem>();
		while(cursor.moveToNext()){
			DownloadItem item = new DownloadItem();
			item.setSid(cursor.getString(0));
			item.setTitle(cursor.getString(1));
			item.setIconPath(cursor.getString(2));
			item.setIconUrl(cursor.getString(3));
			item.setPkgName(cursor.getString(4));
			item.setAvailVersion(cursor.getString(5));
			item.setFileBytes(cursor.getLong(6));
			item.setDownloadUrl(cursor.getString(7));
			item.setFilePath(cursor.getString(8));
			list.add(item);
		}
		cursor.close();
		db.close();
		return list;
	}
}
